import datepicker from 'vue-datepicker'
import extend from 'extend'
import getDatePickerOption from '../../../util/date-picker-option'
import { setMenuType, showMsg, deleteScreen, getScreenDetail, updateScreen } from '../../../vuex/action'

export default {
  name: 'flash-ad-detail',
  data() {
    return {
      ad: {
        id: '',
        name: '',
        startTime: '',
        endTime: '',
        waitTime: '',
        channel: ''
      },
      datePickerOption: getDatePickerOption()
    }
  },
  computed: {
    id() {
      return this.$route.params.id
    },
    saveAdParams() {
      return {
        id: this.ad.id,
        name: this.ad.name,
        startTime: this.ad.startTime,
        endTime: this.ad.endTime,
        waitTime: this.ad.waitTime,
        deviceType: this.ad.deviceType,
        channel: this.ad.channel
      }
    }
  },
  components: {
    'vue-date-picker': datepicker
  },
  vuex: {
    actions: {
      xSetMenuType: setMenuType,
      xShowMsg: showMsg,
      xDeleteScreen: deleteScreen,
      xGetScreenDetail: getScreenDetail,
      xUpdateScreen: updateScreen
    }
  },
  ready() {
    this.xSetMenuType('gao')
    this.xGetScreenDetail(this.id)
      .then((data) => {
        this.ad = data.screen
      })
      .catch((res) => {
        this.xShowMsg({
          type: 'danger',
          content: res.error_msg
        })
      })
  },
  methods: {
    trim(inStr) {
      return inStr.replace(/(^ +)|( +$)/g, '')
    },
    checkValid() {
      var ad = extend(true, {}, this.ad)
      if (this.trim(ad.name).length === 0) {
        return '请填写任务名'
      } else if (ad.startTime.length === 0) {
        return '请填写开始时间'
      } else if (ad.endTime.length === 0) {
        return '请填写结束时间'
      } else if (ad.endTime <= ad.startTime) {
        return '结束时间必须晚于开始时间'
      } else if (ad.waitTime.length === 0) {
        return '请填写闪屏时长'
      }
    },
    deleteAd() {
      this.xDeleteScreen(this.id)
        .then((data) => {
          this.$route.router.go('/')
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    },
    saveAd() {
      var validMsg = this.checkValid()
      if (validMsg) {
        return this.xShowMsg({
          type: 'danger',
          content: validMsg
        })
      }
      this.xUpdateScreen(this.saveAdParams).then((res) => {
        this.xShowMsg({
          type: 'info',
          content: '修改闪屏任务成功！'
        })
        window.location.href = '#/'
      })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
